﻿/****************************************************************
*   作者：Schme
*   CLR版本：4.0.30319.42000
*   创建时间：2017/5/25 9:49:35
*   2017
*   描述说明：
*
*   修改历史：
*
*
*****************************************************************/
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Runtime.Caching;
using Abp.Timing;
using Microsoft.AspNetCore.Http;
using Mt.Site.Core.Base.Utils;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Threading.Tasks;

namespace Mt.Site.Core.VerifyCodes
{
    public class VerifyCodeManager :IVerifyCodeManager
    {
        private const string GetVerificationCodeCacheKey = "App.VerificationCode.Cache";

        private readonly IRepository<VerifyCode, Guid> _verifyCodeRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 单位分钟
        /// </summary>
        public const int DeadLineTime = 60;

        public VerifyCodeManager(
            IRepository<VerifyCode, Guid> verifyCodeRepository, 
            ICacheManager cacheManager,
            IHttpContextAccessor httpContextAccessor)
        {
            _verifyCodeRepository = verifyCodeRepository;
            _cacheManager = cacheManager;
            _httpContextAccessor = httpContextAccessor;
        }


        public async Task<string> GetVerifyCode(string email, VerifyCodeType type)
        {
            var vCode = await _verifyCodeRepository.FirstOrDefaultAsync(c => c.Email == email && c.C_Type == type);

            if (vCode != null)
            {
                DateTime dt1 = Clock.Now;
                if (dt1.Subtract(vCode.SendTime).TotalMinutes > DeadLineTime || vCode.IsActive == false)
                {
                    vCode.VCode = NewCode().ToString();
                    vCode.SendTime = dt1;
                    vCode.IsActive = true;
                    await _verifyCodeRepository.UpdateAsync(vCode);
                }
            }
            else
            {
                vCode = new VerifyCode
                {
                    VCode = NewCode().ToString(),
                    SendTime = Clock.Now,
                    IsActive = true,
                    Email = email,
                    C_Type = type
                };
                await _verifyCodeRepository.InsertAsync(vCode);
            }
            return vCode.VCode;
        }

        private int NewCode()
        {
            return StrongRandomHelper.NextRandom(8999) + 1000;
        }

        public async Task<bool> CheckVerifyCode(string email, VerifyCodeType type,string key)
        {
            var vCode = await _verifyCodeRepository.FirstOrDefaultAsync(c => c.Email == email && c.C_Type == type);

            if (vCode != null)
            {
                DateTime dt1 = Clock.Now;
                if (dt1.Subtract(vCode.SendTime).TotalMinutes <= DeadLineTime && vCode.IsActive == true)
                {
                    if (vCode.VCode == key)
                    {
                        vCode.IsActive = false;
                        await _verifyCodeRepository.UpdateAsync(vCode);
                        return true;
                    }
                }
            }
            return false;
        }

        public async Task<byte[]> GetVerifyCodeAndResponse(bool onlyDigit = false)
        {
            var context = _httpContextAccessor.HttpContext;
            if(context == null)
            {
                throw new Exception("只能用于http请求中");
            }

            string checkCode;
            if (onlyDigit)
            {
                checkCode = NewCode().ToString();
            }
            else
            {
                checkCode = RandomNum(4);
            }

            string sessionId = context.Request.Cookies[MtSiteConsts.CookieNames.SessionCookieName];
            if (sessionId.IsNullOrEmpty())
            {
                //没有使用session功能
                sessionId = Guid.NewGuid().ToString("N");
                context.Response.Cookies.Append(
                    MtSiteConsts.CookieNames.SessionCookieName,
                    sessionId,
                    new CookieOptions
                    {
                        Path = "/",
                        HttpOnly = true
                    }
                 );
            }

            await _cacheManager.GetCache<string, string>(GetVerificationCodeCacheKey).SetAsync(sessionId, checkCode, TimeSpan.FromMinutes(DeadLineTime));

            return CreateCheckCodeImage(checkCode);
        }

        public async Task<bool> CheckVerifyCode(string inputVerifyCode)
        {
            var context = _httpContextAccessor.HttpContext;
            if (context == null)
            {
                throw new Exception("只能用于http请求中");
            }

            string sessionId = context.Request.Cookies[MtSiteConsts.CookieNames.SessionCookieName];
            if (sessionId.IsNullOrEmpty())
            {
                //sessionId读取不到
                return false;
            }


            var item = await _cacheManager.GetCache<string, string>(GetVerificationCodeCacheKey).GetOrDefaultAsync(sessionId);
            return item == inputVerifyCode;
        }

        /// <summary>
        /// 产生随机数
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        private string RandomNum(int n)
        {
            string strchar = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
            //string strchar = "1,2,3,4,5,6,7,8,9,0";

            var val = StrongRandomHelper.GetStrongRandom_Long();

            string[] VcArray = strchar.Split(',');
            string VNum = "";
            for (int i = 1; i < n + 1; i++)
            {
                int t = (int)(val % VcArray.Length);
                val = val / VcArray.Length;
                VNum += VcArray[t];
            }
            return VNum;
        }

        private byte[] CreateCheckCodeImage(string checkCode)
        {
            int width = 50;
            int height = 22;
            Color bgColor = Color.White;
            Color lineColor = Color.Black;
            Font font = new Font("Arial", 12, (FontStyle.Bold));
            Color linearGradientBrushColor1 = Color.Blue;
            Color linearGradientBrushColor2 = Color.DarkRed;
            float linearGradientBrushAngle = 1.5f;
            float x = 2;
            float y = 2;
            Color borderColor = Color.Silver;

            //---
            Bitmap image = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器   
                Random random = new Random();

                //清空图片背景色   
                g.Clear(bgColor);

                //画图片的毕竟噪音线   
                for (int i = 0; i < 2; i++)
                {
                    //产生随机的起始坐标和重点坐标   
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(lineColor), x1, y1, x2, y2);
                }

                // 线性渐变封装   
                LinearGradientBrush brush = new LinearGradientBrush(
                            new Rectangle(0, 0, image.Width, image.Height),
                            linearGradientBrushColor1,
                            linearGradientBrushColor2,
                            linearGradientBrushAngle,
                            true
                        );
                g.DrawString(checkCode, font, brush, x, y);

                // 画图片的前景噪点   
                for (int i = 0; i < 100; i++)
                {
                    int a = random.Next(image.Width);
                    int b = random.Next(image.Height);
                    image.SetPixel(a, b, Color.FromArgb(random.Next()));
                }

                // 花图片的边框线 矩形   
                g.DrawRectangle(new Pen(borderColor), 0, 0, image.Width - 1, image.Height - 1);

                //创建其支持存储区为内存的   
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                return ms.GetBuffer();
            }
            finally
            {
                // 释放资源   
                g.Dispose();
                image.Dispose();
            }
        }
    }
}
